package com.example.snakefinal;

import android.os.Build;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client implements Runnable {
    private String ip;
    private int port = 43991;
    private SnakeGame snakeGame;

    private Socket socket;

    public Client(String ip, SnakeGame snakeGame) throws IOException {
        this.ip = ip;
        this.snakeGame = snakeGame;

    }

    @Override
    public void run() {
        try {
            socket = new Socket(ip, port);
            System.out.println("socket：start");
            Message.HelloMsg object = new Message.HelloMsg();
            object.type = "HelloMsg";
            object.skinResource = snakeGame.mSnake.skinResource;
            sendMessage(object);
            while (true) {
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    bytes = inputStream.readNBytes(ByteUtils.bytesToInt(inputStream.readNBytes(4)));
                }
                callMessage(bytes);
            }
        } catch (IOException e) {
            System.out.println("线程异常");
            System.out.println(e.getMessage());
        }
    }

    public void sendMessage(Object object) throws IOException {
        byte[] bytes = JsonUtil.toStr(object).getBytes();
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(bytes.length);
        outputStream.write(bytes);
        System.out.println("send:" + new String(bytes));
    }

    private void callMessage(byte[] bytes) {
        String msg = new String(bytes);
        System.out.println(msg);
        Message.BasicMsg basicMsg = JsonUtil.fromStr(msg, Message.BasicMsg.class);
        if (basicMsg.type.equals("JoinMsg")) {
            Message.JoinMsg joinMsg = JsonUtil.fromStr(msg, Message.JoinMsg.class);
            snakeGame.mSnake.name = joinMsg.name;
        }
        if (basicMsg.type.equals("AllInfo")) {
            Message.AllInfo joinMsg = JsonUtil.fromStr(msg, Message.AllInfo.class);
            snakeGame.FOOD.clear();
            snakeGame.FOOD.addAll(joinMsg.foods);
            snakeGame.walls = joinMsg.wall;
            snakeGame.huos = joinMsg.huo;
            snakeGame.CURRENT_STATE = joinMsg.state;
            snakeGame.weather = joinMsg.weather;
            snakeGame.loadSnake(joinMsg.snakes);
        }
    }
}
